/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package stack;

import exceptions.EmptyStackException;

/**
 *
 * @author pc
 */
public class ArrayStack<E> implements Stack<E> {

    private E S[];
    private int top = -1;
    public static final int CAPACITY = 1024;
    private int capacity = 1024;
    private int size;

    public ArrayStack() {
        S = (E[]) new Object[CAPACITY];
    }

    public ArrayStack(int cap) {
        capacity = cap;
        S = (E[]) new Object[capacity];
    }

    @Override
    public int size() {
        return top + 1;
    }

    @Override
    public boolean isEmpty() {
        return top == -1 ? true : false;
    }

    @Override
    public E top() throws EmptyStackException {
        if (isEmpty()) {
            new EmptyStackException("Non è possibile prelevare il top, stack vuoto");
        }
        return S[top];
    }

    @Override
    public void push(E x) {
        if (size() == capacity) {
            capacity *= 2;
            E[] newArray = (E[]) new Object[capacity];
            for (int i = 0; i < capacity/2; i++) {
                newArray[i] = S[i];
            }
            S = newArray;
        }
        top = top + 1;
        S[top] = x;
    }

    @Override
    public E pop() throws EmptyStackException {
        if (isEmpty()) {
            throw new EmptyStackException("Impossibile eliminare primo element, stack vuoto");
        }
        E temp = S[top];
        S[top--] = null;
        return temp;
    }
}
